<?php
/*
 * Created on Feb 5, 2009
 * @author: ANH
 * @PARAM rtype is rootType: example: caves is type then attraction is rtype
 * @filesource: modules/place/controllers/PlaceController.php
 */

class Place_IndexController extends Clu_Controller_Action_Hvn
{
	public function init()
	{
		//require_once  (APP_PATH.'/modules/article/Model/Article.php');
		//require_once  (APP_PATH.'/modules/category/Model/Category.php');
		//require_once  (APP_PATH.'/modules/comment/Model/Comment.php');
		//require_once  (APP_PATH.'/modules/user/Model/User.php');
		$this->m = new place_Model_Place();
		$this->mCity = new place_Model_City();
		$this->mDistrict = new place_Model_District();
		$this->mVillage = new place_Model_Village();
		$this->mArticle = new article_Model_Service();
		$this->mCategory = new category_Model_Category();
		$this->mCategory->setTables('place');
		$this->mComment = new comment_Model_Service();
		$this->mVicinity = new place_Model_Vicinity();
		parent::init();
	}
	
    public function newAction() 
    {

       	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'create place') === false)
	    {
	    	$this->view->errorMessage = t(68);
	    	$this->renderToHolder( 'common/error.phtml');
	    	return;
	    }
		
	    //TODO: what for?
    	$auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
	    
        $form = new place_Form_Place();
        $form->cluBuild(array('action' => 'new', 'view' => $this->view, 
							  'userPermissions' => $sess->userPermissions, 
							  'language' => $sess->viewLang ));
     	$this->view->errorMessage = '';
        $formName = 'place_Form_Place';
        $data = $this->_request->getParams();
		//if valid data     
        if ($this->_request->isPost() && $form->isValid($_POST)) 
	    {
	    	//get type 
        	$ret = $this->mCategory->getTree($data['category'], 2, 2);
	    	//TODO: change this to become part of form validation
	    	if($data['category'] == 0 || $data['rtype'] == 0)
	    	{
	    		$this->view->errorMessage .= t(129)." <br/>";
	    	}	
	        else if(!empty($ret) && !empty($data['type']))
	        {
        		$data['type'] = implode(",",$data['type']);
	        }
	        
	        //check: has place already?
	        if(	$this->m->checkPlace($data['name']) === false)
    		{
    			$this->view->errorMessage .= t(722)." <br/>";
    		}
	    		
	        $db = $this->db;
	        $db->beginTransaction();
            try 
            {
            	$t['article_title'] = $data['name'];
				$t['article_language'] = $data['language'];
				$t['article_module'] = 'place';
	        	$t['article_status'] = isset($data['status']) ? $data['status'] : 
        			Zend_Registry::get('configuration')->general->defaultNodeStatus->place;
            	//insert article_title
                if (!$this->mArticle->insertRaw($t,false))
                {
                	$this->view->errorMessage .= t(503);
                }
                $article_id = $db->lastInsertId();
                
                //insert place
    			if($article_id != 0)
                {
                	$data['article_id'] = $article_id;
	                $data['poster_id'] = $uIdentity->id;
		            try
			    	{
			    		$options = array('do_validate' => false);
		    			$placeId = $this->m->insertRaw($data, $options);
			    	}
			    	catch (Exception $e) 
			    	{
			    		$this->mArticle->deleteByPrimary(array($article_id), false);
			    	    $this->view->errorMessage .= $e->getMessage() . "<br/>" . t(723);
			    	}
                }
                else
                {
                	die($this->view->errorMessage);
                }
                 
                 $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollBack();
                $this->view->errorMessage .= $e->getMessage() . "<br/>". t(69);
            }
            if (empty($this->view->errorMessage)) //SUCCESSFUL
            {
    	    	$url = $this->view->hvnUrl(array('module'=>'place', 'action'=>'edit'));
    			$this->_helper->redirector->gotoUrl($url . '?id='.$placeId.'&j=1'); //TODO
            	return;
            }
		}
		else
			$this->view->errorMessage .= t(1);
		
		//Populate form & rtype options 
        $categoryId = $this->_request->getParam("category");
        $form->populateCategory($data, $categoryId );
		
        $this->view->form = $form;
        $this->view->lang = $data['lang'];
		if(!empty($data['type']))
	        $this->view->type = $data['type'];
        $this->view->mode = "new";
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
			
        $mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
        $this->renderToHolder( 'index/new.phtml', false, null, 4, 1);
    }
    
    public function viewAction() 
    {
        $placeId = $this->_request->getParam("id");
		$sess = new Zend_Session_Namespace(CLU_NS);
		$dataDisplay = $this->m->getData($placeId, $options = null);
		$data = unserialize($dataDisplay['metadata']);
		$dataplace = array('city_id' => $dataDisplay['city_id'],'district_id' => $dataDisplay['district_id'],
						   'rtype' => $dataDisplay['rtype'], 'type' => $dataDisplay['type']);
		$sess->searchParams->place = $dataplace;
        /*
        if(!$dataDisplay)
        {
            $this->view->errorMessage = t(724);
            $this->renderToHolder( 'common/error.phtml', false, null, 4, 1);	
        }
        if(!empty($dataDisplay))
        {
	        //get data for display
	        if ($dataDisplay['article_data']['article_language'] != $sess->viewLang)
	            $this->view->errorMessage = sprintf(t(519),  $sess->viewLang );
	        $place['article'] = $dataDisplay['article_data'];
	        //die_a($dataDisplay);
	        $this->view->place = $dataDisplay;
	        $this->view->categoryName = $dataDisplay['category_name']['name'];
	        $a = array();
	        if(isset($dataDisplay['type_name']))
	        {
		        foreach($dataDisplay['type_name'] as $k => $v)
		        {
			        $a[] = $v['name'];
		        }
	        }
	        $this->view->typeName = $a;
	        $this->view->lang = $sess->viewLang;
	        $this->view->oriLang = $dataDisplay['article_data']['article_language'];
	        $this->renderToHolder('index/view.phtml', false, null, 4, 2);
        	*/
        if(isset($dataDisplay['district_id']))
        	$districtId = $dataDisplay['district_id'];
        else
        	$districtId = null;
        if(isset($data['city_name']))
        	$cityName = $data['city_name'];
        else
        	$cityName = null;
        if(isset($data['district_name']))
        	$districtName = $data['district_name'];
        else
        	$districtName = null;
        if(isset($dataDisplay['rtype']))
        	$rtype = $dataDisplay['rtype'];
        else
        	$rtype = null;
        if(isset($dataDisplay['type']))
        	$type = $dataDisplay['type'];
        else
        	$type = null;
        if(isset($data['rtype_name']))
        	$rtypeName = $data['rtype_name'];
        else
        	$rtypeName = null;
        if(isset($data['type_name']))
        	$typeName = $data['type_name'];
        else
        	$typeName = null;
        	
        $autoLink = array(
        					'module' => 'common',
        					'controller' => 'block',
        					'action' => 'autoLink',
        					'city_id' => $dataDisplay['city_id'],
        					'district_id' => $districtId,
        					'city_name' => $cityName,
        					'district_name' => $districtName,
        					'rtype' => $rtype,
        					'type' => $type,
        					'rtypeName' => $rtypeName,
        					'typeName' => $typeName,
        					'placeName' => $dataDisplay['article_data']['article_title'],
        					'regionId' => 3,
        					'boxWeight' => 2,
        );
        $this->addMiniAction($autoLink);
        
    	$viewDataRequest = array(
                            'module' => 'place',
                            'controller' => 'block',
                            'action' => 'viewPlace',
                            'id' => $placeId,
                            'data' => $dataDisplay,
                            'regionId' => 4,
                            'boxWeight' => 1,
            );
		$this->addMiniAction($viewDataRequest);
		
    	$loginRequest = array(
                            'module' => 'user',
                            'controller' => 'block',
                            'action' => 'login',
                            'regionId' => 1,
                            'boxWeight' => 1,
							'theme' => 'second'
            );
		$this->addMiniAction($loginRequest);
		
		$tabMenuRequest = array(
                            'module' => 'place',
                            'controller' => 'block',
                            'action' => 'tabMenu',
                            'regionId' => 4,
                            'boxWeight' => 7,
                            'id' => $placeId,
                            'type' => $dataDisplay['type'],
                            'page' => 'view-place',
							'uid' => $dataDisplay['poster_id']
            );
		$this->addMiniAction($tabMenuRequest);
	
		$advertiseRequest = array(
                            'module' => 'place',
                            'controller' => 'block',
                            'action' => 'listCategoryOfCity',
                            'regionId' => 4,
                            'boxWeight' => 9,
                            'city_id' => $dataDisplay['city_id'],
                            'district_id' => $dataDisplay['district_id'],
                            'city_name' => $cityName,
                            'district_name' => $districtName,
                            'page' => 'view-place',
            );
		$this->addMiniAction($advertiseRequest);

//		$advertiseRequest = array(
//                            'module' => 'place',
//                            'controller' => 'block',
//                            'action' => 'advertise',
//                            'regionId' => 4,
//                            'boxWeight' => 9,
//                            'page' => 'view-place',
//            );
//		$this->addMiniAction($advertiseRequest);
	
        $placeSimpleSearchRequest = array(
			'module' => 'place',
			'controller' => 'block',
			'action' => 'simpleSearch',
			'regionId' => 3,
			'boxWeight' => 1,
			'data' => $dataDisplay,
		);
		$this->addMiniAction($placeSimpleSearchRequest);
		
		//block map
//		$mapRequest = array(
//				'module' => 'hvn',
//				'controller' => 'block',
//				'action' => 'mapPlace',
//				'regionId' => 6,
//				'boxWeight' => 1,
//				'placeId' => $placeId,
//				'category_rtype' =>  $dataDisplay['rtype']
//		);
//		$this->addMiniAction($mapRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
			
//        //block event					
//		$eventRequest = array(
//				'module' => 'event',
//				'controller' => 'block',
//				'action' => 'relatedPlace',
//				'regionId' => 6,
//				'boxWeight' => 2,
//				'placeId' => $placeId,
//				'uid' => $dataDisplay['poster_id']
//		);
//		$this->addMiniAction($eventRequest);
			
	        /*
			$placeInCityRequest = array(
					'module' => 'place',
					'controller' => 'block',
					'action' => 'placeInCity',
					'regionId' => 5,
					'boxWeight' => 4,
					'placeId' => $placeId,
					'city_id' =>  $dataDisplay['city_id'],
					'category_rtype' =>  $dataDisplay['rtype']
			);
			$this->addMiniAction($placeInCityRequest);
			
			$topInCityRequest = array(
					'module' => 'place',
					'controller' => 'block',
					'action' => 'topInCity',
					'regionId' => 4,
					'boxWeight' => 8,
					'city_id' =>  $dataDisplay['city_id'],
					'type1'  => '45', //top retaurant
					'type2'  => '54' //top cinema
			);
			$this->addMiniAction($topInCityRequest);
			
			//block tour					
			$tourRequest = array(
					'module' => 'tour',
					'controller' => 'block',
					'action' => 'relatedTour',
					'regionId' => 4,//6,
					'boxWeight' => 2,//3,
					'poster_id' => $dataDisplay['poster_id']
			);
			$this->addMiniAction($tourRequest);
			*/
			
			//block gallery 
			$mainGalleryRequest = array(
					'module' => 'file',
					'controller' => 'block',
					'action' => 'imageList',
					'regionId' => 6,
					'boxWeight' => 3,
					'poster_id' => $dataDisplay['poster_id'],
					'c' => 'place',
					't' => 'image',
					'uid' => $dataDisplay['poster_id'],
					'id'  => $dataDisplay['id'],
					'galleryId' => 'main-gallery-place-' . $dataDisplay['id'],
					
			);
			$this->addMiniAction($mainGalleryRequest );
	    	
		if($dataDisplay['type'] == 45)
		{
			$listRestaurantRequest = array(
						'module' => 'place',
						'controller' => 'block',
						'action' => 'listRestaurant',
						'regionId' => 6,
						'boxWeight' => 1,
						'category_rtype' => 20,
						'type' => 45,
						'page' => 'view-place',
				);
		$this->addMiniAction($listRestaurantRequest);
		}
		
		$gMapRequest = array(
					'module' => 'devel',
					'controller' => 'block',
					'action' => 'gMap',
					'regionId' => 6,
					'boxWeight' => 4,
			);
		$this->addMiniAction($gMapRequest);
    }

    public function editAction()
    {
        $placeId = $this->_request->getParam('id');
        if (!$p = $this->m->findByPrimary($placeId))
        {
        	$this->view->errorMessage = t(725);
        }
        //check for permission here. Check rights
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ((isset($uIdentity->id) != $p->poster_id && strpos($sess->userPermissions, 'update place') === false) ||
				(isset($uIdentity->id) == $p->poster_id && strpos ($sess->userPermissions, 'update own place') === false))
		{
		 	$this->view->errorMessage = t(726);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		
		if ($this->_request->getParam('j') == 1)
        {
        	$this->view->justMessage = true;
        }
        $form = new place_Form_EditPlace();
        $form->cluBuild(array('action' => 'update', 'rtype' => $p->rtype, 'view' => $this->view,
        					  'userPermissions' => $sess->userPermissions, 'category' =>$p->rtype ));
        $formName = 'place_Form_EditPlace';
        if (!$this->_request->isPost())
        {
			//$fData = $this->m->getData($placeId, true, true);
            $form->populate($this->m->transformToFormArray($formName, $p));
        }
        else if ( $form->isValid($_POST))
        {
	    	$data = $this->_request->getParams();
        	// insert article
            $articleData = array();
            $articleData['article_title'] = $p->name;
            $keys = array('article_body', 'article_originality');
	        $articleData = clu_array_merge($keys, $data);
            
            if (!($this->mArticle->saveRaw(null, $articleData, $p->article_id, false)))
            {
            	$this->view->errorMessage .= t(503);
            	$this->renderToHolder('common/error.phtml', false, null, 4, 1);
            }
			//all data was prepared. Now save the place data
		    try
		    {
		    	$this->m->saveRaw($p, $data, $placeId, array('do_validate' => false));
		    }
		    catch (Exception $e) 
            {
            	$this->view->errorMessage = t(727);
                $this->renderToHolder('common/error.phtml', false, null, 4,1);
            }
	        $this->view->successMessage = t(728);
			//populate form
			$form->populate($this->m->transformToFormArray($formName, $p));
        }
        else
        {
	    	$this->view->errorMessage = t(71);
	    	$this->renderToHolder('common/error.phtml', false, null, 4, 1);
        }
        
        //get city_name and district_name
        $dataDisplay = $this->m->getData($placeId, $options = null );
        if(!empty($dataDisplay['city_name']))
			$this->view->city_name = $dataDisplay['city_name'];
		if(!empty($dataDisplay['district_name']))
			$this->view->district_name = $dataDisplay['district_name'];
		$this->view->form = $form;      
        $this->view->id = $placeId;
        $this->view->placeName = $p->name;
        if(!empty($uIdentity->id))
        	$this->view->uid = $uIdentity->id;
        $this->view->rtype = $p->rtype;
        $this->view->mode = "edit";
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
			
        $mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
        $this->renderToHolder( 'index/edit.phtml', false, null, 4, 1);                 
    }
    
    public function deleteAction() 
    {
        $id = $this->_request->getParam('id');
        if (!$p = $this->m->findByPrimary($id))
        {
        	$this->view->errorMessage = t(725);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        if(!$this->m->deleteByPrimary($p))
        {
        	$this->view->errorMessage = t(729);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        $this->renderToHolder( 'common/success.phtml');
		
    }

 	public function searchAction()
    {
    	$requestData = $this->_request->getParams();
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$data = $this->prepareSearchData($requestData);
    	print_r($data);
    	$form = new place_Form_PlaceSearch();
		if (strpos($sess->userPermissions, "administer place"))
			$cluSearchMode = "fullAdminSearch";
	    else
			$cluSearchMode = "fullSearch";
        $form->cluBuild(array('action' => 'search', 'view' => $this->view, 'cluSearchMode' => $cluSearchMode));
        $sess->searchParams->place = $data;
        
        if (isset($data['clu_search']) || $this->_request->isPost())
        {
		   	$select = $this->m->search($data);
		   	echo "<hr/>". $select->__toString() . "<hr/>";
			$paginator = $this->generatePaginator($select, $data['page'], $data['place_perpage'], 7, 'Jumping');
			$form->populateCategory($data);
        }
        else
        {
			if (!empty($data['page']) )
	        {
	           $data = $sess->searchParams->place;
	           if(isset($data))
	           {
           			$select = $this->m->search($data);
           			$paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['place_perpage'], 
           													7, 'Jumping');
					$form->populateCategory($data);
	           }
	        }
	        //else it is the first time populateing teh search form
        }
       //the search form, with populated data if any
		$this->view->form = $form; 
		
		$this->view->listCategory = $this->mCategory->getRootType('Root_Place');
		
		
		if(isset($data['category']))
		{
			$this->view->categoryId = $data['category'];
			$this->view->listRtype = $this->mCategory->getTree($data['category'], 1, 1);
		}
		if(!empty($data['rtype']))
		{
			$this->view->rtype = $data['rtype'];
			$this->view->listType = $this->mCategory->getTree($data['rtype'], 1, 1);
		}

		if(!empty($data['type']))
		{
			if(is_array($data['type']))
			{
				$this->view->type = $data['type'];
	    		foreach($data['type'] as $t)
					$subType = $this->mCategory->getTree($t, 1, 1);
			}
			else
				$this->view->type = $data['type'];
				
			if(count($data['type']) > 1 && $data['rtype'] != 0)
				$this->view->sub_type = $this->mCategory->getTree($data['type']['0'], 1, 1);

			if(!empty($subType))
				$this->view->sub_type = $subType;
		}
		//get city
		$this->view->listCity = $this->mCity->fetchAll()->toArray();
		if(!empty($data['city_id']))
		{
			$this->view->cityId = $data['city_id'];
			$this->view->cityName = $this->mCity->getCityName($data['city_id']);
			$this->view->listDistrict = $this->mDistrict->getDistricts($data['city_id']);
			if(!empty($data['district_id']))
			{
				$this->view->districtId = $data['district_id'];
				$this->view->districtName = $this->mDistrict->getDistrictName($data['district_id']);
			}
		}
			
		$this->view->mode = 'search';
		$this->renderToHolder('index/'.$cluSearchMode . '.phtml', false, null, 4, 1);
       
       //the results
       if(isset($paginator))
       {	
	       	$this->view->paginator = $paginator;
			$this->view->pList = $paginator->getCurrentItems();
			//get articles
			$articleList = array();
			$mArticle = new article_Model_Service();
			foreach ($this->view->pList as $p)
			{
				$articleList[$p['id']] = $mArticle->getArticleData($p['article_id']);
			}
			$this->view->aList = $articleList;

			$t = $this->_request->getParam('page');
			$pageNum  = !empty($t) ? $t : 1; 
			$perPage = isset($data['place_perpage']) ? $data['place_perpage']:  $data['place_perpage'];
			$this->view->startIndex = $perPage * ($pageNum - 1);
			$this->view->numberOfItems = $paginator->getTotalItemCount();
			$this->view->perPage = $perPage;
			$this->view->pageNum = $pageNum;
			$this->view->numberOfPages = ceil($this->view->numberOfItems/$this->view->perPage);  
	       	//$this->renderToHolder('index/list_admin.phtml');
	       	$this->renderToHolder('index/list.phtml', false, null, 4, 2);
       }
       
       $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$placeSimpleSearchRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
				'data' => $data,
		);
		$this->addMiniAction($placeSimpleSearchRequest);
		
		$tourRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'topPlaceList',
                                'regionId' => 6,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($tourRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
//		$infoSupportRequest = array(
//				'module' => 'common',
//				'controller' => 'block',
//				'action' => 'infoSupport',
//				'regionId' => 5,
//				'boxWeight' => 3,
//		);
//		$this->addMiniAction($infoSupportRequest);
		
		/*
		$topCityRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'topCityMarquee',
				'regionId' => 4,
				'boxWeight' => 0,
		);
		$this->addMiniAction($topCityRequest);
       */
    }
    
    public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
		$paginator->setItemCountPerPage($itemsPerPage);
		$paginator->setCurrentPageNumber($pageNumber);
		$paginator->setPageRange($pageRange);
		Zend_Paginator::setDefaultScrollingStyle($style);
		return $paginator;
    }
    
    public function successAction()
    {
        $this->view->placeId = $this->_request->getParam("lastInsertId");
        $this->renderToHolder('common/success.phtml');
    }
    
	public function editBasicAction()
    {
        $placeId = $this->_request->getParam('id');
        if (!$p = $this->m->findByPrimary($placeId))
        	$this->view->errorMessage = t(725);

        //check for permission here. Check rights
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ((isset($uIdentity->id) != $p->poster_id && strpos ($sess->userPermissions, 'update place') === false) ||
				(isset($uIdentity->id) == $p->poster_id && strpos ($sess->userPermissions, 'update own place') === false))
		{
		 	$this->view->errorMessage = t(726);
		}
        
        $form = new place_Form_Place();
        $form->cluBuild(array('action' => 'edit-basic', 'view' => $this->view, 
							  'userPermissions' => $sess->userPermissions));
		$formName = 'place_Form_Place';
		$this->view->form = $form;    
		if (!$this->_request->isPost())
		{
			$options = array('get_article' => true, 'get_vicinities' => false);
			$data = $this->m->getData($placeId, $options);
	        $categoryId = $this->mCategory->findParentId($data['rtype']);
			$form->populate($this->m->transformToFormArray($formName, $p));
			$form->populateCategory( $data, $categoryId);
		}
		
        elseif ($form->isValid($_POST))
        {	
        	$data = $this->_request->getParams();
        	$data['poster_id'] = $uIdentity->id;
        	// update article
        	$articleData = $this->m->transformToFormArray($formName, $p);
        	$articleData['article_title'] = $data['name'];
        	$articleData['article_language'] = $data['language'];
//        	die_a($articleData);
            if (!($this->mArticle->saveRaw(null, $articleData, $articleData['article_id'], false)))
            {
            	$this->view->errorMessage .= t(503);
            }
		    try
		    {
		    	if(!empty($data['type']))
		    		$data['type'] = implode(',', $data['type']);
		    	if ($this->m->saveRaw($p, $data, $placeId, false))
	            {
	            	$this->view->successMessage = t(731);
	            }
		    	
		    }
		    catch (Exception $e) 
            {
                $this->view->errorMessage .= t(727);
            }
	        
	        $form->populateCategory( $data, $data['category'] );
        }
        else
        {
        	$this->view->errorMessage = t(71);
        }
        	
        $this->view->id = $placeId;
        $this->view->rtype = $p->rtype;
        $this->view->placeName = $p->name;
        $this->view->type = explode(',',$p->type);
        $this->view->mode = "edit";
        $this->view->name = isset($uIdentity->name);
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
			
        $mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
        $this->renderToHolder( 'index/new.phtml', false, null, 4, 1);                 
    }    
    
    public function galleryAction()
    {
        $placeId = $this->_request->getParam('id');
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
        if (!$p = $this->m->findByPrimary($placeId))
        {
        	$this->view->errorMessage = t(725);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        $this->view->id = $placeId;
        $this->view->uid = $p->poster_id;
        $this->view->placeName = $p->name;
        $this->renderToHolder( 'index/gallery.phtml');                 
    }
    
    public function travelInfoAction()
    {
    	$this->view->placeholder('currentPage')->set('info');
    	
    	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
    	$placeSimpleSearchRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($placeSimpleSearchRequest);
		
		/*
		$travelRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'travelInfo',
                                'regionId' => 5,
                                'boxWeight' => 1,
								'category' => 6,
								'block' => 5
       	);
		$this->addMiniAction($travelRequest);
		
		$travelInfoRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'travelInfo',
                                'regionId' => 4,
                                'boxWeight' => 1,
								'category' => 6,
								'block' => 4
       	);
		$this->addMiniAction($travelInfoRequest);
		*/
		$ActractionRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'travelInfo',
                                'regionId' => 4,
                                'boxWeight' => 2,
								'category' => 5,
								'block' => 4
       	);
		$this->addMiniAction($ActractionRequest);
		
   		 $actractionRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'travelInfo',
                                'regionId' => 6,
                                'boxWeight' => 1,
								'category' => 5,
								'block' => 5
       	);
		$this->addMiniAction($actractionRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
    }
    
    public function homeAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$placeSimpleSearchRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'simpleSearch',
				'regionId' => 3,
				'boxWeight' => 1,
		);
		$this->addMiniAction($placeSimpleSearchRequest);
		
		$subMenuRequest = array(
				'module' => 'place',
				'controller' => 'block',
				'action' => 'subMenu',
				'regionId' => 3,
				'boxWeight' => 2,
				'page' => 'place',
		);
		$this->addMiniAction($subMenuRequest);
		
		$placeRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'featuredList',
                                'regionId' => 4,
                                'boxWeight' => 1,
								'page' => 'home'
                );
		$this->addMiniAction($placeRequest);
		
		$advertiseRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'advertise',
                                'regionId' => 4,
                                'boxWeight' => 2,
                                'page' => 'place',
                );
		$this->addMiniAction($advertiseRequest);
		
		$neighborhoodRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'neighborhood',
                                'regionId' => 4,
                                'boxWeight' => 3,
                                'page' => 'place',
                );
		$this->addMiniAction($neighborhoodRequest);
		
        $mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		/*
		$listHotelRequest = array(
					'module' => 'place',
					'controller' => 'block',
					'action' => 'listHotel',
					'regionId' => 4,
					'boxWeight' => 4,
					'rtype' => 13,
			);
		$this->addMiniAction($listHotelRequest);
		*/
		/*
		$mainMenuRequest = array(
                                'module' => 'hvn',
                                'controller' => 'block',
                                'action' => 'mainMenu',
                                'regionId' => 1,
                                'boxWeight' => 1,
                );
		$this->addMiniAction($mainMenuRequest);
		*/
		$tabMenuRequest = array(
                                'module' => 'place',
                                'controller' => 'block',
                                'action' => 'tabMenu',
                                'regionId' => 4,
                                'boxWeight' => 3,
                                'page' => 'place',
                );
		$this->addMiniAction($tabMenuRequest);
		
		$listRestaurantRequest = array(
					'module' => 'place',
					'controller' => 'block',
					'action' => 'listRestaurant',
					'regionId' => 4,
					'boxWeight' => 4,
					'category_rtype' => 20,
					'type' => 45,
					'page' => 'home-place',
			);
		$this->addMiniAction($listRestaurantRequest);
		
		$listNatureRequest = array(
					'module' => 'place',
					'controller' => 'block',
					'action' => 'listNature',
					'regionId' => 4,
					'boxWeight' => 5,
					'rtype' => array(17,18,20,21),
					'page' => 'place',
			);
		$this->addMiniAction($listNatureRequest);
	}
	
	/**
	 * This function merges all the previously saved search data & request params
	 * 
	 * @param: $requestData The search params that user submitted
	 * @return: Void Or $currentSearchData ?? TODO
	 */
	public function prepareSearchData($requestData)
	{
		$keys = array('language', 'id', 'raw_name','unaccented_name',
					  'article_id','fee','to_fee', 'other_name',
                      'fee_basis','fee_currency','payment_method', 'meals', 'delivery',
        	          'built_year','to_built_year', 'status', 'rating', 'desc',
        	          'rating_count', 'ASCorDESC', 'orderBy', 'user_id', 'getArticle');
		//other keys: 'city_id','district_id','village_id', 'str_number','str_name'
		//'type','rtype', 
		$sess = new Zend_Session_Namespace(CLU_NS);
		if(isset($sess->searchParams->place))
			$currentSearchData = $sess->searchParams->place;
//		die_a($currentSearchData);
		//place list + pagination
		if (isset($requestData['place_perpage']))
			$currentSearchData['place_perpage'] = $requestData['place_perpage'];
		
		else if (!isset($currentSearchData['place_perpage']))
				$currentSearchData['place_perpage'] = $requestData['place_perpage'] = 10;
			else
			 	$requestData['place_perpage'] = $currentSearchData['place_perpage'];
			
		if (isset($requestData['page']))
			$currentSearchData['page'] = $requestData['page'];
		else
			$currentSearchData['page'] = $requestData['page'] = 1;
		
		if(isset($requestData['clu_search']))
			$currentSearchData['clu_search'] = $requestData['clu_search'];
		
		//reset all params in session		
		if(isset($requestData['reset']) && $requestData['reset'] == 1)
		{
			//filter keyword
			$currentSearchData = $this->filterKeyword($requestData);
			return $currentSearchData ;
		}
		
		//No reset detected, now merge common keys first & don't unset values
		$currentSearchData = $this->mergeSearchValues($requestData, $currentSearchData, $keys, false); 
		
		//Address 
		$addressKeys = array(
						0 => 'city_id',
						1 => 'district_id',
						2 => 'village_id',
						3 => 'address5',
						4 => 'address6',
						5 => 'address7', //'str_name', 
						6 => 'address8', //TODO: get all 9 fields from address. See misc/docs/db.txt
						7 => 'address9'
					); 
		$currentSearchData = $this->mergeHierarchySearchValues($requestData, $currentSearchData, $addressKeys, 3);
		//type & rtype
		$categoryKeys = array(
						0 => 'category',
						1 => 'rtype',
						2 => 'type',
			);
		$currentSearchData = $this->mergeHierarchySearchValues($requestData, $currentSearchData, $categoryKeys, 2);
		
		//remove empty fields
		foreach ($currentSearchData as $k => $v)
		{
			if (empty($v))
				unset($currentSearchData[$k]);
		}
		
		//filter keyword
		$currentSearchData = $this->filterKeyword($currentSearchData);
		
		if(isset($requestData['category']) && !isset($requestData['rtype']))
			return $requestData;
			
		return $currentSearchData;
	}
	
	/**
	 * Take $currentSearchData['raw_name'] to generate category (rtype, type)
	 * and a new name search $currentSearchData['name'] if needed
	 * 	For example : search with keyword "Tran Quoc Pagoda" will result in
	 * 		keyword = "Tran Quoc",
	 * 		category = "Pagoda" (e.g. 12 );
	 * 
	 * @TODO: Process city as well, for example "Tran Quoc Pagoda, Hanoi";
	 * @param $currentSearchData ....
	 * @return array with $currentSearchData['name'] present
	 * 
	 */
	public function filterKeyword($currentSearchData)
	{
		if(isset($currentSearchData['raw_name']))
		{
			$userInput = $currentSearchData['raw_name'];
			//replace double white spaces with one white space character
			$str = preg_replace('/\s\s+/', ' ', $userInput );
			$strInput = strtolower(VN_unaccent(trim($str)));
			$filterKeywords = array('7' => 'khach san 1 sao',
									'8' => 'khach san 2 sao',
									'9' => 'khach san 3 sao',
									'10' => 'khach san 4 sao', 
									'11' => 'khach san 5 sao',
									'12' => 'nha nghi',
									'13' => 'khach san',
									'30' => 'chua',
									'45' => 'nha hang',
									'47' => 'bar',
									'48' => 'cafe',
									);
			foreach($filterKeywords as $key => $val)
			{
				if(strncmp($strInput, $val, strlen($val)) == 0)
				{
					$currentSearchData['name'] = trim(str_replace($val, "",$strInput));
					$ret = $this->mCategory->getTree($key, 0, 1);
					foreach($ret as $k => $v)
					{
						$count = count(explode('_', $v['tree_path']));
						if($count == 5 && empty($currentSearchData['rtype']))
							$currentSearchData['rtype'] = $key;
						else if($count == 6)
						{
							$currentSearchData['rtype'] = $v['pid'];
							$currentSearchData['type'] = $v['id'];
						}
					}
					break;
				}
			}
			return $currentSearchData;
		}
		else
			return $currentSearchData;
	}
	
	public function unsetSearchValues($currentSearchData, $arrayKeys)
	{
		foreach($arrayKeys as $k)
			unset($currentSearchData[$k]);
	}
	
	public function mergeSearchValues($requestData, $currentSearchData, $arrayKeys, $unset)
	{
		foreach($arrayKeys as $k)
		{
			if (isset($requestData[$k]) && !empty($requestData[$k]))
				$currentSearchData[$k] = $requestData[$k];
			else if ($unset)	
				unset($currentSearchData[$k]);
			//else, keep the $currentSearchData[$k]
		}
		return $currentSearchData;
	}
	
	public function mergeHierarchySearchValues($requestData, $currentSearchData, $addressKeys, $indexToUnset)
	{
		foreach ($addressKeys as $keyIndex => $key)
		{
			if (!isset($requestData[$key]))
				continue;
			//now isset($requestData[$key]) == true
			else
			{
				//echo "<h1> $keyIndex : $key </h1> current search data: $currentSearchData[$key] <br/> request data {$requestData[$key]} <hr/>";
				if (
						($keyIndex < $indexToUnset) // in range that will cause reset
						&& 
						(
							(isset($currentSearchData[$key]) && ($requestData[$key] != $currentSearchData[$key]))
								||
							(!isset($currentSearchData[$key]))
						)
					)
				{
					//change key value first
					$currentSearchData[$key] = $requestData[$key];
					$addressKeysToUnset = array();
					//$keyToUnset = $addressKeys' subarray from $keyIndex + 1 -> last
					for ($i = $keyIndex + 1; $i < count($addressKeys); $i++)
					{
						$addressKeysToUnset [] = $addressKeys[$i];
					}
					$currentSearchData = $this->mergeSearchValues($requestData, $currentSearchData, $addressKeysToUnset , true);
					//if value of $keyIndex is empty then unset value of $keyIndex+1
					if(empty($requestData[$key]) || $requestData[$key] == -2000)
					{
						unset($currentSearchData[$key]);
						unset($currentSearchData[$addressKeys[$keyIndex+1]]);
					}
					break; //break after merge & unset the remaining values
				}
				else //only set 1 value
				{
					if ($requestData[$key] == -1000 )
						unset($currentSearchData[$key]);
					else
						$currentSearchData[$key] = $requestData[$key];
				}
			} 
		}
//		die_a($currentSearchData);
		return $currentSearchData;
	}
}
?>
